<template>

  <div style="height: 100%;" :style="{height: !isPhone ? '100%' : 'auto'}">
    <!--    手机端聊天-->
    <div class="bg" ref="chat" :style="{height: mheight,position:'absolute'}" v-if="isPhone">
      <van-pull-refresh v-model="isLoading" success-text="加载完成" @refresh="onRefresh">
        <div class="chat-content">
          <div class="live-count" v-if="liveLinePeople">{{liveLinePeople}}人{{isEnd?'':'正在'}}观看</div>
          <!-- recordContent 聊天记录数组-->
          <div v-for="(itemc,indexc) in recordContent" :key="indexc">
            <!-- 对方 -->
            <div class="word" style="padding: 0.2rem 0 0 0;">
              <img src="../assets1/header.png" />
              <div class="info" style="text-align: left;">
                <p class="time">{{itemc.name}} {{itemc.insertTime}}</p>
                <div class="info-content" style="display: inline-block;">{{itemc.content}}</div>
              </div>
            </div>
          </div>
        </div>
      </van-pull-refresh>
      <van-field style="position: fixed;bottom: 0px;" class="field" v-model="sms" center clearable placeholder="参与讨论，为大会助力..........">
        <template #button>
          <van-button size="small" type="info" :loading="btn_loading" loading-type="spinner" loading-text="发送中..." @click="sendSms">
            <Icon type="ios-paper-plane" style="font-size: 20px;"/>
          </van-button>
        </template>
      </van-field>
    </div>


    <!--    PC端聊天-->
    <div v-else style="height: 100%;position: relative;">
<!--      <div class="live-title">聊天互动</div>-->
      <div class="live-count1">{{liveLinePeople}}人{{isEnd?'':'正在'}}观看</div>
      <div class="ltBg1" style="max-height: calc(100% - 70px);margin: 0 0 10px 0;">
        <div class="ltBg1_div" ref="chat">
          <van-pull-refresh v-model="isLoading" success-text="加载完成" @refresh="onRefresh" >
            <div class="chat-content">
              <div v-for="(itemc,indexc) in recordContent" :key="indexc" style="padding: 10px 0 0 0;">
                <div class="word1">
                  <img src="../assets1/header.png" />
                  <div class="info" style="text-align: left;">
                    <p class="time">{{itemc.name}} {{itemc.insertTime}}</p>
                    <div class="info-content" style="display: inline-block;">{{itemc.content}}</div>
                  </div>
                </div>
              </div>
            </div>
          </van-pull-refresh>
        </div>

      </div>
      <van-field class="_wz_field field" style="height: 60px;" v-model="sms" center placeholder="参与讨论，为大会助力.........." @keyup.enter="sendSms">
        <template #button>
          <Button size="small" type="primary" :loading="btn_loading" loading-type="spinner" loading-text="发送中..." @click="sendSms" style="border-radius: 50%;color: #fff;background: #3795fc;width: 33px;height: 33px;display: flex;align-items: center;justify-content: center;">
            <Icon type="ios-paper-plane" style="font-size: 20px;"/>
          </Button>
        </template>
      </van-field>

<!--      <returnIndex :isPhone="$store.state.isMobile" style="position: absolute;"></returnIndex>-->
<!--      <returnDay :isPhone="$store.state.isMobile" style="position: absolute;"></returnDay>-->
    </div>
    <peoplePopup ref="peoplePopup"></peoplePopup>
  </div>
</template>
<script>
import webScoket from "@/components/webScoket";
import peoplePopup from "@/components/peoplePopup.vue";
import MsgBus from "../utils/bus";
import returnIndex from "@/components/return";
import returnDay from "@/components/returnDay";
export default {
  props: ["msgHeight", "msgWidth", "isPhone"],
  mixins: [webScoket],
  components: {
    returnIndex,//返回首页
    returnDay,//跳转会议
    peoplePopup,//登录使用
  },
  data() {
    return {
      sms: "",
      mheight: "",
      mid: "", //会议id
      count: 1,
      liveLinePeople: 0,
      isLoading: false,
      myWebsocketKey: "",
      recordContent: [],
      btn_loading: false, //按钮loading
      isEnd: true
    };
  },
  computed: {//计算属性

  },
  beforeCreate() {//beforeCreate创建前状态

  },
  created() {//created创建完毕状态

  },
  beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

  },
  mounted() {//mounted 挂载结束状态
    let that = this;
    //获取会议
    that.mid = that.getQueryName("type");
    //当是pc端是获取屏幕的宽度
    // if (!that.isPhone) {
      // that.mwidth = that.$refs.chat.offsetWidth + "px";
      that.$refs.chat.addEventListener("scroll", that.getScroll);
    // }
    MsgBus.$on("sendIsEnd", e => {
      that.isEnd = e;
    });
    //获取聊天消息
    that.getChatList();
  },
  methods: {//执行的方法
    // scrollToBottom() {
    //   let that = this;
    //   that.$nextTick(() => {
    //     var container = that.$el.querySelector("chat-content");
    //     container.scrollTop = container.scrollHeight;
    //   });
    // },
    //上拉加载
    getScroll(e) {
      let that = this;
      if (that.$refs.chat.scrollTop == 0) {
        that.onRefresh();
      }
      // console.log(that.$refs.chat.scrollTop);
    },
    //上拉刷新
    onRefresh() {
      let that = this;
      that.count++;
      that.getChatList();
    },
    //发送信息
    sendSms() {
      let that = this;
      //判断用户是否登录
      if (!localStorage.getItem("userId")) {
        that.$refs.peoplePopup.open(that.isPhone);
      } else {
        that.checkUser(() => {
          //判断用户id是否过期

          if (that.sms == "") {
            that.$that.$toast("消息不能为空");
            return;
          }
          that.btn_loading = true;
          that.http.sendChat({meetingId: that.mid, content: that.sms, userId: localStorage.getItem("userId")}).then(res => {
            that.$that.$toast(res.message);
            if (res.status == 1000) {
              that.sms = "";
              that.btn_loading = false;
              that.updated();
              //成功后重新拿聊天记录
              // that.getChatList();
            }
          }).catch(err => {
            that.btn_loading = false;
          });
        });
      }
    },
    //检验用户是否过期
    checkUser(fn) {
      let that = this;
      that.$toast.loading({message: "加载中...", forbidClick: true});
      that.http.checkUserId({userId: localStorage.getItem("userId")}).then(res => {
        that.$toast.clear();
        if (res.status == 1103) {
          that.$refs.peoplePopup.open(that.isPhone);
          // that.$that.$toast("登录已过期，请重新登录");
        } else {
          fn();
        }
      }).catch(err => {
        that.$toast.clear();
      });
    },
    enter(flag) {
      let that = this;
      that.pushPage(`${flag}`);
    },
    //更新消息弹框
    updated() {
      let that = this;
      that.$nextTick(() => {
        that.$refs.chat.scrollTop = that.$refs.chat.scrollHeight;
      });
    },
    //获取消息列表 少名字
    getChatList() {
      let that = this;
      that.$toast.loading({message: "加载中...", forbidClick: true});
      that.http.getChats({meetingId: that.mid, size: 20, current: that.count}).then(res => {
        that.$toast.clear();
        if (res.status == 1000) {
          that.recordContent = [...res.data.records, ...that.recordContent];
          that.isLoading = false;
        }
      }).catch(err => {
      });
    },
    websocketonmessage(e) {
      let that = this;
      that.longstart();
      try {

        var news = JSON.parse(e.data);
        // console.log(news)
        if(!!news.type && news.type == 'del'){  // 需要删除



          var arr = JSON.parse(JSON.stringify(that.recordContent));
          var len = arr.length-1;

          for(var i = len ; i >= 0 ; i--){
            if(arr[i].chatCode == news.value){
              arr.splice(i,1);
            }
          }

          that.recordContent = arr

          return false;
        }


        if (news.count) {
          that.liveLinePeople = news.count;
          return;
        }
        if (news.replay) {
          MsgBus.$emit("sendMsg", { type: 1, msg: news.replay });
          return;
        }
        if (news.secondsEnd) {
          MsgBus.$emit("sendMsg", { type: 2, msg: news.secondsEnd });
          return;
        }
        var flag = that.recordContent.filter(item => {
          return item.chatId == news.chatId;
        });
        if (flag.length == 0) {
          news.insertTime = news.time;
          // console.log(news.insertDate);
          that.recordContent.push(news);

          that.updated();
        }
      } catch (err) {
        return;
      }
    }
  },
  watch: {//监听
    msgHeight(val) {
      let that = this;
      that.mheight = val + "px";
    },
    recordContent(val) {
      let that = this;
      if (that.count == 1) {
        that.updated();
      }
      that.sms = "";
    }
  },
  beforeUpdate() {//beforeUpdate 更新前状态

  },
  updated() {//updated 更新完成状态

  },
  beforeDestroy() {//beforeDestroy 销毁前状态
    let that = this;
    window.removeEventListener("scroll", that.getScroll, true);
  },
  destroyed() {//destroyed 销毁完成状态

  }
}
</script>

<style lang="scss" scoped>
.dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  background: #277fff;
  border-radius: 50%;
  margin-right: 10px;
  margin-left: 20px;
}
.live-count {
  position: fixed;
  right: 0.1rem;
  background: #e6eaf3;
  border-radius: 0.3rem;
  height: 0.6rem;
  line-height: 0.6rem;
  padding: 0 0.2rem;
  font-size: 0.2rem;
  color: #666;
}
.live-count1 {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #e6eaf3;
  border-radius: 0.3rem;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  font-size: 12px;
  color: #666;
  z-index: 10;
}
.live-title {
  height: 0.6rem;
  line-height: 0.6rem;
  text-align: center;
  background: #d1e9fc;
  font-weight: 600;
  font-size: 16px;
  letter-spacing: 2px;
}
.bg {
  height: 100%;
  width: 100%;
  overflow-y: scroll;
  bottom: 50px;
  background-size: cover;
  background-image: url(../assets1/bg.jpg);
}
.bg::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
.ltBg1 {
  height: 100%;
  width: 100%;
  //overflow-y: scroll;
  bottom: 50px;
  background-image: url(../assets1/er/pc/ltBack.png);
  background-size: cover;
  .ltBg1_div{
    height: 100%;
    //height: calc(100% - 46px);
    overflow-y: scroll;
  }
  .ltBg1_div::-webkit-scrollbar {
    width: 0px;
    height: 0px;
  }
}
.chat-content {
  padding: 10px;
  .word1 {
    display: flex;
    min-height: 80px;
  }
  .word {
    display: flex;
    min-height: 1.35rem;
  }
  img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .info {
    margin-left: 10px;
    .time {
      font-size: 12px;
      color: rgba(51, 51, 51, 0.8);
      margin: 0;
      height: 20px;
      line-height: 20px;
      margin-top: -5px;
      text-align: left;
    }
    .info-content {
      max-width: 3rem;
      padding: 10px;
      font-size: 14px;
      background: #fff;
      text-align: left;
      position: relative;
      border-radius: 0.1rem;
      color: #333;
      word-break: break-all;
    }
    //小三角形
    .info-content::before {
      position: absolute;
      left: -8px;
      top: 8px;
      content: "";
      border-right: 10px solid #fff;
      border-top: 8px solid transparent;
      border-bottom: 8px solid transparent;
    }
  }

}

</style>

<style lang="scss">
._wz_field{
  .van-field__control{
    padding: 6px 16px;
    border: 1px solid #9da0a4;
  }
  .ivu-btn-primary{
    border: 0px;
  }
  button{
    padding: 6px 16px;
  }
}
</style>
